package com.boomshake.controller;

import com.boomshake.common.Result;
import com.boomshake.service.DistributorService;
import com.boomshake.vo.CommissionDetailVO;
import com.boomshake.vo.DistributorStatisticsVO;
import com.boomshake.vo.DistributorTreeVO;
import com.boomshake.utils.JwtUtil;
import com.boomshake.vo.DistributorVO;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

/**
 * 分销员管理控制器
 */
@Slf4j
@RestController
@RequestMapping("/admin/distributor")
@RequiredArgsConstructor
@CrossOrigin(origins = {"http://localhost:5173", "http://localhost:5174", "http://127.0.0.1:5173", "http://127.0.0.1:5174"}, allowCredentials = "true", maxAge = 3600)
public class AdminDistributorController {

    private final DistributorService distributorService;

    @Autowired
    private JwtUtil jwtUtil;

    /**
     * 获取分销员树形结构
     * @param storeId 门店ID（可选）
     * @param level 分销等级（可选）
     * @param status 状态（可选）
     * @return 分销员树形结构列表
     */
    @GetMapping("/tree")
    public Result<List<DistributorTreeVO>> getDistributorTree(
            @RequestParam(required = false) Long storeId,
            @RequestParam(required = false) Integer level,
            @RequestParam(required = false) Integer status) {
        try {
            List<DistributorTreeVO> result = distributorService.getDistributorTree(storeId, level, status);
            return Result.success(result);
        } catch (Exception e) {
            log.error("获取分销员树形结构失败", e);
            return Result.error("获取分销员树形结构失败: " + e.getMessage());
        }
    }

    /**
     * 获取分销员详情
     * @param distributorId 分销员ID
     * @return 分销员详情
     */
    @GetMapping("/{distributorId}")
    public Result<DistributorTreeVO> getDistributorDetail(@PathVariable String distributorId) {
        try {
            // 参数验证
            if (distributorId == null || "undefined".equals(distributorId) || distributorId.trim().isEmpty()) {
                return Result.error("分销员ID不能为空");
            }
            
            Long id;
            try {
                id = Long.parseLong(distributorId);
            } catch (NumberFormatException e) {
                log.warn("无效的分销员ID: {}", distributorId);
                return Result.error("无效的分销员ID: " + distributorId);
            }
            
            if (id <= 0) {
                return Result.error("分销员ID必须大于0");
            }
            
            DistributorTreeVO result = distributorService.getDistributorDetail(id);
            if (result == null) {
                return Result.error("分销员不存在");
            }
            return Result.success(result);
        } catch (Exception e) {
            log.error("获取分销员详情失败, distributorId: {}", distributorId, e);
            return Result.error("获取分销员详情失败: " + e.getMessage());
        }
    }

    /**
     * 获取分销员佣金明细
     * @param distributorId 分销员ID
     * @param page 页码
     * @param size 每页大小
     * @return 佣金明细
     */
    @GetMapping("/{distributorId}/commission-details")
    public Result<CommissionDetailVO> getDistributorCommissionDetails(
            @PathVariable String distributorId,
            @RequestParam(defaultValue = "1") Integer page,
            @RequestParam(defaultValue = "10") Integer size) {
        try {
            // 参数验证
            if (distributorId == null || "undefined".equals(distributorId) || distributorId.trim().isEmpty()) {
                return Result.error("分销员ID不能为空");
            }
            
            Long id;
            try {
                id = Long.parseLong(distributorId);
            } catch (NumberFormatException e) {
                log.warn("无效的分销员ID: {}", distributorId);
                return Result.error("无效的分销员ID: " + distributorId);
            }
            
            if (id <= 0) {
                return Result.error("分销员ID必须大于0");
            }
            
            CommissionDetailVO result = distributorService.getDistributorCommissionDetails(id, page, size);
            return Result.success(result);
        } catch (Exception e) {
            log.error("获取分销员佣金明细失败, distributorId: {}", distributorId, e);
            return Result.error("获取分销员佣金明细失败: " + e.getMessage());
        }
    }

    /**
     * 更新分销员状态
     * @param distributorId 分销员ID
     * @param request 状态更新请求
     * @return 操作结果
     */
    @PatchMapping("/{distributorId}/status")
    public Result<String> updateDistributorStatus(
            @PathVariable String distributorId,
            @RequestBody StatusUpdateRequest request) {
        try {
            // 参数验证
            if (distributorId == null || "undefined".equals(distributorId) || distributorId.trim().isEmpty()) {
                return Result.error("分销员ID不能为空");
            }
            
            Long id;
            try {
                id = Long.parseLong(distributorId);
            } catch (NumberFormatException e) {
                log.warn("无效的分销员ID: {}", distributorId);
                return Result.error("无效的分销员ID: " + distributorId);
            }
            
            if (id <= 0) {
                return Result.error("分销员ID必须大于0");
            }
            
            if (request.getStatus() == null) {
                return Result.error("状态参数不能为空");
            }
            
            if (request.getStatus() != 0 && request.getStatus() != 1) {
                return Result.error("状态参数无效，只能是0或1");
            }
            
            boolean success = distributorService.updateDistributorStatus(id, request.getStatus());
            if (success) {
                return Result.success("分销员状态更新成功");
            } else {
                return Result.error("分销员状态更新失败");
            }
        } catch (Exception e) {
            log.error("更新分销员状态失败, distributorId: {}, status: {}", distributorId, request.getStatus(), e);
            return Result.error("更新分销员状态失败: " + e.getMessage());
        }
    }

    /**
     * 获取分销员统计信息
     * @param storeId 门店ID（可选）
     * @param level 分销等级（可选）
     * @param status 状态（可选）
     * @return 统计信息
     */
    @GetMapping("/statistics")
    public Result<DistributorStatisticsVO> getDistributorStatistics(
            @RequestParam(required = false) Long storeId,
            @RequestParam(required = false) Integer level,
            @RequestParam(required = false) Integer status) {
        try {
            DistributorStatisticsVO result = distributorService.getDistributorStatistics(storeId, level, status);
            return Result.success(result);
        } catch (Exception e) {
            log.error("获取分销员统计信息失败", e);
            return Result.error("获取分销员统计信息失败: " + e.getMessage());
        }
    }

    /**
     * 获取门店分销员列表
     */
    @GetMapping("/store/{storeId}/list")
    public Result<List<DistributorVO>> getStoreDistributors(@PathVariable Long storeId, HttpServletRequest request) {
        try {
            // 获取当前管理员ID
            getCurrentAdminId(request);
            
            List<DistributorVO> distributors = distributorService.getStoreDistributors(storeId);
            return Result.success(distributors);
        } catch (Exception e) {
            log.error("获取门店分销员列表失败", e);
            return Result.error("获取门店分销员列表失败：" + e.getMessage());
        }
    }

    /**
     * 从请求中获取当前管理员ID
     */
    private Long getCurrentAdminId(HttpServletRequest request) {
        String authHeader = request.getHeader("Authorization");
        String token = jwtUtil.getTokenFromHeader(authHeader);
        
        if (token == null || !jwtUtil.validateToken(token)) {
            throw new RuntimeException("token无效或已过期，请重新登录");
        }
        
        return jwtUtil.getUserIdFromToken(token);
    }

    /**
     * 状态更新请求DTO
     */
    public static class StatusUpdateRequest {
        private Integer status;

        public Integer getStatus() {
            return status;
        }

        public void setStatus(Integer status) {
            this.status = status;
        }
    }
} 